package cn.zsb.zsb.service;

import cn.zsb.zsb.dao.AdvtiseMapper;
import cn.zsb.zsb.dao.OperMapper;
import cn.zsb.zsb.entity.Advtise;
import cn.zsb.zsb.entity.AdvtiseExample;
import cn.zsb.zsb.entity.Operate;
import cn.zsb.zsb.entity.Suser;
import cn.zsb.zsb.util.StrUtil;
import cn.zsb.zsb.vo.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@Service
@Transactional(readOnly = true)
public class AdvtiseService {
    @Autowired
    AdvtiseMapper mapper;

    @Autowired
    private OperMapper operMapper;

    //两步操作，1：增加广告！2：增加一个操作记录
    @Transactional(readOnly = false,rollbackFor = {Exception.class})
    public int add(Advtise adv) {
        int r= this.mapper.insertSelective(adv);
        Operate op=new Operate();
        op.setOper("增加广告");
        op.setUsername("老吴");
        op.setAddtime(new Date());
        this.operMapper.add(op);
        //System.out.println(5/0);
        return r;
    }

    public Page<Advtise> search(String title, String url, Date start, Date end, int page, int size) {

        com.github.pagehelper.Page<Suser> p = PageHelper.startPage(page, size);

        AdvtiseExample admin = new AdvtiseExample();
        AdvtiseExample.Criteria cr = admin.createCriteria();
        if (!StrUtil.isBlank(title))
            cr.andTitleLike("%" + title + "%");
        if (!StrUtil.isBlank(url))
            cr.andUrlLike("%" + url + "%");
        if (!StrUtil.isBlank(start))
            cr.andStarttimeGreaterThanOrEqualTo(start);
        if (!StrUtil.isBlank(end))
            cr.andStarttimeLessThanOrEqualTo(end);
        List<Advtise> list = mapper.selectByExample(admin);
        return new Page<Advtise>(p.getTotal(), page, size, list);
    }

}
